extends Node
class_name BattleSystem

# 战斗状态枚举
enum BattleState {
	INITIALIZING,  # 初始化战斗
	PLAYER_TURN,   # 玩家回合
	ENEMY_TURN,    # 敌人回合
	ANIMATING,     # 动画播放中
	VICTORY,       # 战斗胜利
	DEFEAT,        # 战斗失败
	FLEEING,       # 逃跑中
	PAUSED         # 暂停中
}

# 当前战斗状态
var current_state: int = BattleState.INITIALIZING

# 暂停前的状态
var previous_state: int = BattleState.INITIALIZING

# 是否暂停
var is_paused: bool = false

# 战斗参与者
var player: Player

# 设置暂停状态
func set_paused(paused: bool) -> void:
	if paused and not is_paused:
		# 保存当前状态并暂停
		previous_state = current_state
		current_state = BattleState.PAUSED
		is_paused = true
	elif not paused and is_paused:
		# 恢复之前的状态
		current_state = previous_state
		is_paused = false
var enemies: Array = []  # 敌人列表

# 回合计数
var turn_count: int = 0

# 战斗日志
var battle_log: Array = []

# 战斗结果信号
signal battle_ended(victory: bool, rewards: Dictionary)
signal turn_changed(turn: int, is_player_turn: bool)
signal action_performed(performer, target, action, result)

# 初始化战斗
func initialize_battle(p_player: Player, p_enemies: Array) -> void:
	player = p_player
	enemies = p_enemies
	turn_count = 0
	battle_log = []
	
	# 记录战斗开始
	add_to_log("战斗开始！")
	for enemy in enemies:
		add_to_log("一个%s出现了！" % enemy.enemy_name)
	
	# 设置初始状态
	current_state = BattleState.PLAYER_TURN
	
	# 发出回合变化信号
	emit_signal("turn_changed", turn_count, true)

# 执行玩家行动
func execute_player_action(action_type: String, action_index: int = -1, target_index: int = 0) -> void:
	# 检查是否是玩家回合
	if current_state != BattleState.PLAYER_TURN:
		return
	
	# 检查目标是否有效
	if target_index < 0 or target_index >= enemies.size():
		target_index = 0  # 默认攻击第一个敌人
	
	var target = enemies[target_index]
	
	# 根据行动类型执行不同操作
	match action_type:
		"attack":
			_execute_attack(player, target)
		"skill":
			if action_index >= 0 and action_index < player.skills.size():
				_execute_skill(player, target, player.skills[action_index])
			else:
				add_to_log("无效的技能选择！")
				return
		"item":
			if action_index >= 0 and action_index < player.inventory.size():
				var item = player.inventory[action_index]
				if item.use(player):
					add_to_log("%s 使用了 %s！" % [player.player_name, item.item_name])
					emit_signal("action_performed", player, player, "item", {"item_name": item.item_name})
				else:
					add_to_log("无法使用该物品！")
					return
			else:
				add_to_log("无效的物品选择！")
				return
		"flee":
			_attempt_flee()
			return
		_:
			add_to_log("无效的行动！")
			return
	
	# 检查战斗是否结束
	if _check_battle_end():
		return
	
	# 切换到敌人回合
	current_state = BattleState.ENEMY_TURN
	emit_signal("turn_changed", turn_count, false)
	
	# 执行敌人行动
	_execute_enemy_actions()

# 执行普通攻击
func _execute_attack(attacker, defender) -> void:
	# 计算伤害
	var damage = max(1, attacker.attack - defender.defense / 2)
	
	# 应用伤害
	defender.current_health -= damage
	
	# 记录战斗日志，根据对象类型选择正确的名称属性
	var attacker_name = attacker.player_name if attacker is Player else attacker.enemy_name
	var defender_name = defender.player_name if defender is Player else defender.enemy_name
	add_to_log("%s 攻击了 %s，造成了 %d 点伤害！" % [attacker_name, defender_name, damage])
	
	# 检查目标是否被击败
	if defender.current_health <= 0:
		defender.current_health = 0
		add_to_log("%s 被击败了！" % (defender.player_name if defender is Player else defender.enemy_name))
		
		# 如果是敌人被击败，从列表中移除
		if defender != player:
			enemies.erase(defender)
	
	# 发出行动信号
	emit_signal("action_performed", attacker, defender, "attack", {"damage": damage})

# 执行技能
func _execute_skill(attacker, defender, skill) -> void:
	# 检查真气是否足够
	if attacker.current_spirit < skill.spirit_cost:
		add_to_log("%s 真气不足，无法使用 %s！" % [attacker.player_name, skill.skill_name])
		return
	
	# 检查技能是否在冷却中
	if skill.current_cooldown > 0:
		add_to_log("%s 正在冷却中，无法使用！" % skill.skill_name)
		return
	
	# 消耗真气
	attacker.current_spirit -= skill.spirit_cost
	
	# 设置技能冷却
	skill.current_cooldown = skill.cooldown
	
	# 根据技能类型执行不同效果
	var result = {}
	
	# 获取攻击者和防御者的名称
	var attacker_name = attacker.player_name if attacker is Player else attacker.enemy_name
	var defender_name = defender.player_name if defender is Player else defender.enemy_name
	
	match skill.skill_type:
		Skill.SkillType.ATTACK:
			# 计算技能伤害
			var base_stat = 0
			match skill.scaling_stat:
				"attack": base_stat = attacker.attack
				"spirit": base_stat = attacker.max_spirit
				_: base_stat = attacker.attack
			
			var damage = skill.base_power + int(base_stat * skill.scaling_factor)
			defender.current_health -= damage
			
			add_to_log("%s 使用了 %s，对 %s 造成了 %d 点伤害！" % 
				[attacker_name, skill.skill_name, defender_name, damage])
			
			result = {"damage": damage}
			
			# 检查目标是否被击败
			if defender.current_health <= 0:
				defender.current_health = 0
				add_to_log("%s 被击败了！" % defender_name)
				
				# 如果是敌人被击败，从列表中移除
				if defender != player:
					enemies.erase(defender)
		
		Skill.SkillType.HEAL:
			# 治疗效果
			var heal_amount = skill.base_power
			defender.current_health = min(defender.current_health + heal_amount, defender.max_health)
			
			add_to_log("%s 使用了 %s，为 %s 恢复了 %d 点生命！" % 
				[attacker_name, skill.skill_name, defender_name, heal_amount])
			
			result = {"heal": heal_amount}
		
		Skill.SkillType.BUFF:
			# 增益效果（简化版）
			add_to_log("%s 使用了 %s，强化了 %s！" % 
				[attacker_name, skill.skill_name, defender_name])
			
			result = {"buff": true}
		
		Skill.SkillType.DEBUFF:
			# 减益效果（简化版）
			add_to_log("%s 使用了 %s，削弱了 %s！" % 
				[attacker_name, skill.skill_name, defender_name])
			
			result = {"debuff": true}
	
	# 发出行动信号
	emit_signal("action_performed", attacker, defender, "skill", result)

# 尝试逃跑
func _attempt_flee() -> bool:
	# 简单的逃跑机制，有50%的成功率
	var flee_chance = 0.5
	
	# 根据玩家的速度和敌人的速度调整逃跑几率
	var avg_enemy_speed = 0
	for enemy in enemies:
		avg_enemy_speed += enemy.speed
	
	if enemies.size() > 0:
		avg_enemy_speed /= enemies.size()
	
	flee_chance += (player.speed - avg_enemy_speed) * 0.05
	flee_chance = clamp(flee_chance, 0.1, 0.9)
	
	if randf() < flee_chance:
		# 逃跑成功
		add_to_log("你成功逃脱了战斗！")
		# 设置战斗状态为逃跑中
		current_state = BattleState.FLEEING
		# 发出战斗结束信号，没有奖励
		emit_signal("battle_ended", false, {})
		return true
	else:
		# 逃跑失败
		add_to_log("逃跑失败！")
		# 切换到敌人回合
		current_state = BattleState.ENEMY_TURN
		emit_signal("turn_changed", turn_count, false)
		# 执行敌人行动
		_execute_enemy_actions()
		return false

# 添加战斗日志
func add_to_log(message: String) -> void:
	# 将消息添加到战斗日志数组
	battle_log.append(message)
	
	# 发出信号通知UI更新
	emit_signal("action_performed", null, null, "log", {"message": message})

# 检查战斗是否结束
func _check_battle_end() -> bool:
	# 检查玩家是否被击败
	if player.current_health <= 0:
		current_state = BattleState.DEFEAT
		add_to_log("你被击败了！")
		emit_signal("battle_ended", false, {})
		return true
	
	# 检查是否击败所有敌人
	if enemies.size() == 0:
		current_state = BattleState.VICTORY
		# 计算战斗奖励（简化版）
		var rewards = {
			"experience": 100,
			"spirit_stones": 50
		}
		add_to_log("战斗胜利！获得了奖励！")
		emit_signal("battle_ended", true, rewards)
		return true
	
	return false

# 执行敌人行动
func _execute_enemy_actions() -> void:
	# 增加回合计数
	turn_count += 1
	
	# 遍历所有存活的敌人
	for enemy in enemies:
		# 简单的AI决策：当真气充足且有可用技能时，有30%几率使用技能
		var use_skill = randf() < 0.3 and enemy.current_spirit > 0 and enemy.skills.size() > 0
		
		if use_skill:
			# 随机选择一个技能
			var skill_index = randi() % enemy.skills.size()
			var skill = enemy.skills[skill_index]
			
			# 检查是否有足够的真气使用技能
			if enemy.current_spirit >= skill.spirit_cost and skill.current_cooldown <= 0:
				_execute_skill(enemy, player, skill)
			else:
				# 如果无法使用技能，则使用普通攻击
				_execute_attack(enemy, player)
		else:
			# 使用普通攻击
			_execute_attack(enemy, player)
		
		# 检查战斗是否结束
		if _check_battle_end():
			return
	
	# 如果战斗未结束，切换回玩家回合
	if current_state == BattleState.ENEMY_TURN:
		current_state = BattleState.PLAYER_TURN
		emit_signal("turn_changed", turn_count, true)
